package com.x.epspace.common;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.QueryResults;
import org.springframework.stereotype.Service;

import com.x.epspace.dao.MessagesDao;
import com.x.epspace.entity.BindEnt;
import com.x.epspace.entity.Messages;
import com.x.epspace.entity.RegUser;

@Service("messageOper")
public class MessagesOper {
	
	@Resource
	private MessagesDao messagesDao;
	
	/**
	 * 获得当前登录用户绑定企业，最新消息时间
	 * @param bindEnt
	 * @return
	 */
	public long getMaxScnTime(BindEnt bindEnt) {
		long scnTime = 0;
		Query<Messages> qm = messagesDao.createQuery().order("-scnTime");
		qm.field("bindEnt").equal(bindEnt);
		QueryResults<Messages> msgResults = messagesDao.find(qm);
		if (msgResults.countAll()>0) {
			List<Messages> msgList = msgResults.asList();
			scnTime = msgList.get(0).getScnTime();
		}
		return scnTime;
	}
	
	/*
	 * 通过webservices获得该企业相关消息提醒，封装到List<MessageObj>
	 */
	public void saveEntInfor(RegUser regUser, BindEnt bindEnt, long lTime) {
		
		String strJson = "";
		
    //服务的地址
    URL wsUrl;
		try {
			wsUrl = new URL(AppConfig.getProperty("url", "webService") + "?entId=" + bindEnt.getSnbxh() + "&scnTime=" + lTime);
			HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
	    
	    conn.setDoInput(true);
	    conn.setDoOutput(true);
	    conn.setRequestMethod("POST");
	    conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
	    
	    OutputStream os = conn.getOutputStream();
	    //请求体
	    String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://ws.itcast.cn/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + 
	                  "<soapenv:Body> <q0:sayHello><arg0>aaa</arg0>  </q0:sayHello> </soapenv:Body> </soapenv:Envelope>";
	    os.write(soap.getBytes());
	    InputStream is = conn.getInputStream();
	    
	    byte[] b = new byte[1024];
	    int len = 0;
	    while((len = is.read(b)) != -1){
	        String ss = new String(b,0,len,"UTF-8");
	        strJson += ss;
	    }
	    is.close();
	    os.close();
	    conn.disconnect();
	    
	    //解析从webservices获得的json数据
	    JSONObject dataJson = JSONObject.fromObject(strJson);
	    String rowtotal = (String) dataJson.get("rowtotal");
	    JSONArray jsonArray=dataJson.getJSONArray("messages");
	    
	    //写入时间
	    long operTime = System.currentTimeMillis();
	    
	    if (Integer.valueOf(rowtotal) > 0) {
	    	for (int i=0; i<jsonArray.size(); i++) {
	    		JSONObject jsonObj = jsonArray.getJSONObject(i);
		    	Messages msg = new Messages();	    	
		    	msg.setMsg(jsonObj.getString("msg"));
		    	msg.setMsgTypeDesc(jsonObj.getString("msgTypeDesc"));
		    	msg.setPushTime(jsonObj.getString("pushTime"));
		    	msg.setScnTime(jsonObj.getLong("scnTime"));
		    	msg.setRegUser(regUser);
		    	msg.setBindEnt(bindEnt);
		    	msg.setIsRead("0");
		    	msg.setOperTime(operTime);
		    	msg.setMsgjson(jsonObj.toString());
		    	messagesDao.save(msg);
		    }
	    }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
